package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"k8s.io/apimachinery/pkg/util/yaml"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"virtual-resource-schedule-service/global"
)

// GetEnvInfo 获取当前环境变量
func GetEnvInfo(env string) string {
	viper.AutomaticEnv()
	return viper.GetString(env)
}

// InitConfig 初始化config
func InitConfig() {
	// 确定当前使用哪个环境
	virtualEnv := GetEnvInfo("VIRTUAL_ENV")
	configFilePrefix := "config"
	configFileName := fmt.Sprintf("%s-%s.yml", configFilePrefix, virtualEnv)

	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		fmt.Println("无法获取可执行文件路径：", err)
	}
	path, err := filepath.Abs(file)
	if err != nil {
		fmt.Println("无法获取文件绝对路径：", err)
	}
	index := strings.LastIndex(path, string(os.PathSeparator))
	if index == -1 {
		fmt.Println("路径分隔符未找到")
	}
	path = path[:index]
	configFileName = filepath.Join(path, configFileName)

	// 处理配置文件
	v := viper.New()
	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	// 使用全局变量方便后续使用
	if err := v.Unmarshal(global.NacosConfig); err != nil {
		panic(err)
	}
	//zap.S().Infof("配置信息: &v", global.NacosConfig)
	// 从Nacos中读取配置信息
	sc := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   global.NacosConfig.Port,
		},
	}
	cc := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.Namespace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "logs/nacos/log",
		CacheDir:            "cache/nacos/cache",
		LogLevel:            "info",
	}
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(nil)
	}
	// 获取配置信息
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})
	if err != nil {
		panic(err)
	}
	//zap.S().Infof("Nacos content: %+v", content)
	// 转为对象
	err = yaml.Unmarshal([]byte(content), &global.ServerConfig)
	if err != nil {
		zap.S().Fatalf("读取Nacos配置文件失败: %s", err.Error())
	}
	marshal, err := json.Marshal(*global.ServerConfig)
	zap.S().Debugf("server config from nacos: %s", marshal)
}
